package net.gilgame.bukkit;

import net.gilgame.bukkit.commands.*;
import net.gilgame.bukkit.lib.Messages;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

/**
 *
 * @author Gilgame
 * @date 27 November 2011
 */
public class CommandHandler
{
    public boolean run(CommandSender sender, Command command, String label, String[] args)
    {
        String commandName = command.getName().toLowerCase();

        if (!hasPermission(sender, command))
        {
            sender.sendMessage(Messages.NoCAccess);
            return true;
        }

        if (commandName.equals("clearentity"))
        {
            return new ClearEntity().run(sender, args);
        }

        if (command.getName().equals("clearentitynear"))
        {
            return new ClearEntityNear().run(sender, args);
        }

        if (command.getName().equals("countentity"))
        {
            return new CountEntity().run(sender, args);
        }

        if (command.getName().equals("countentitynear"))
        {
            return new CountEntityNear().run(sender, args);
        }

        if (command.getName().equals("findentity"))
        {
            return new FindEntity().run(sender, args);
        }

        return true;
    }

    public static boolean hasPermission(CommandSender sender, Command command)
    {
        String commandName = command.getName().toLowerCase();

        if (!(sender instanceof Player))
        {
            return true;
        }

        if (sender.isOp())
        {
            return true;
        }

        if (sender.hasPermission("entityadmin.*"))
        {
            return true;
        }

        if (sender.hasPermission("entityadmin." + commandName))
        {
            return true;
        }

        return false;
    }

    public static boolean hasPermission(CommandSender sender, String entity)
    {
        if (!(sender instanceof Player))
        {
            return true;
        }

        if (sender.isOp())
        {
            return true;
        }

        if (sender.hasPermission("entityadmin.*"))
        {
            return true;
        }

        if (sender.hasPermission("entityadmin.entity.*"))
        {
            return true;
        }

        if (sender.hasPermission("entityadmin.entity." + entity))
        {
            return true;
        }

        return false;
    }
}
